﻿// =================================================================== 
// 项目说明
//====================================================================
// lsc @Copy Right 2019
// 文件： GcChatMessageRepository.cs
// 项目名称：斑马车务
// 创建时间：2019/10/28
// 负责人：lsc
// ===================================================================
using System;
using System.Text;
using System.Collections.Generic;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using Dapper;

namespace YouWei.Infrastructure.Repository
{
	/// <summary>
	///聊天信息 仓储层
	/// </summary>	
	public class GcChatMessageRepository:BaseRepository<GcChatMessage>
	{		
    
        #region 构造

        public GcChatMessageRepository() : base(){}

        public GcChatMessageRepository(string connectionString) : base(connectionString){}

        public GcChatMessageRepository(DatabaseContext dbContext) : base(dbContext){}

        #endregion

        /// <summary>
        /// 根据发送时间、组ID获取最近10条消息
        /// </summary>
        /// <param name="BrandID"></param>
        /// <returns></returns>

        public List<GcChatMessage> GetTop10LatestInfoBySendTime(DateTime sendTime,int groupId)
        {
            StringBuilder sb = new StringBuilder("SELECT top 10 * FROM GcChatMessage with(nolock) ");
            sb.Append(" WHERE  client_time>=@client_time AND GroupID=@GroupID ORDER BY client_time ASC");
            return Query(sb.ToString(), new { client_time = sendTime, GroupID=groupId });
        }

        public List<GcChatMessage> GetTop10LatestInfoBySendTime(int groupId)
        {
            StringBuilder sb = new StringBuilder("SELECT top 20 * FROM GcChatMessage with(nolock) ");
            sb.Append(" WHERE  GroupID=@GroupID ORDER BY client_time DESC");
            return Query(sb.ToString(), new { GroupID = groupId });
        }

        /// <summary>
        /// 根据时间获取聊天信息
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<WxMessageInfo> GetListByTime(DateTime dt)
        {
            StringBuilder sql = new StringBuilder("SELECT u.nickname as UserNickName,ul.Text,m.groupid,g.nickname as GroupName FROM GcChatMessage m LEFT JOIN GcGroup g ON m.GroupID = g.GroupID LEFT JOIN GcGroupUser u ON m.from_wxid = u.wxid and u.GroupID = m.GroupID and m.to_wxid = g.wxid LEFT JOIN GcMsgContentText ul ON m.MessageID = ul.MessageID WHERE m.CreatedTime > @CreatedTime order by m.CreatedTime ASC");
            DynamicParameters dparams = new DynamicParameters();
            dparams.Add("@CreatedTime", dt, System.Data.DbType.DateTime);
            return dbContext.Connection.Query<WxMessageInfo>(sql.ToString(), dparams).AsList();
        }
    }
}